package com.ldk.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.base.framework.common.CustomException;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.ExpressOrder;
import com.ldk.framework.enums.ExpressOrderStatus;
import com.ldk.framework.service.IExpressOrderService;
import com.ldk.framework.service.IPushMessageService;

/**
 * 快递订单控制器
 * @author xiangwl
 * 2017年2月24日
 * com.ldk.admin.controller
 * ExpressOrderController
 */
@Controller
@RequestMapping("/express")
public class ExpressOrderController extends BaseController {
	/**
	 * 路由地址
	 */
	private final String route = "express";
	/**
	 * 模块名称
	 */
	private final String module = "快递订单";

	@Autowired
	private IExpressOrderService expressOrderService;
	@Autowired
	private IPushMessageService pushMessageService;
	
	@RequestMapping("/list")
	//public ModelAndView list(ModelMap map){
	public ModelAndView list(ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, "", "", module+"管理", "/"+route+"/list", "", "");
		map.addAttribute("route", route);
		map.addAttribute("module", module);

		//操作日志
		//this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/express/list_sj");
		} else {
			return new ModelAndView("/express/list");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<ExpressOrder> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
									       @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
									       @RequestParam(value="searchKey",required=false,defaultValue="") String searchKey,
									       HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		ExpressOrder query = new ExpressOrder();
		if(!StringUtils.isBlank(searchKey)){
			query.setSearchKey(searchKey);
		}
		CustomPageable pageable = new CustomPageable(offset, limit);
		
		Page<ExpressOrder> result = expressOrderService.selectPageList("", query, pageable);
		
		LigerUIGridResult<ExpressOrder> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	/**
	 * 浏览
	 * @param orderNo
	 * @param map
	 * @return
	 */
	@RequestMapping("/view/{orderNo}")
	public ModelAndView view(@PathVariable String orderNo, ModelMap map,HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setViewMode(map, ViewMode.View);
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(orderNo);
		ExpressOrder model = expressOrderService.selectByKey("", query);
		
		map.addAttribute("module", module);
		
		return new ModelAndView("/express/info","model", model);
	}
	
	/**
	 * 配送
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping("/delivery/{orderNo}")
	public ModelAndView delivery(@PathVariable String orderNo, ModelMap map,HttpServletRequest request,
								 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(orderNo);
		ExpressOrder model = expressOrderService.selectByKey("", query);
		if(model == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "快递配送", "/"+route+"/delivery/"+orderNo, "", "");
		setForm(map, "/"+route+"/delivery/submit", null);
		map.addAttribute("module", module);
		
		return new ModelAndView("/express/delivery","model", model);
	}
	
	/**
	 * 指定配送信息提交
	 * @param model
	 * @param redAttr
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping("/delivery/submit")
	public ModelAndView deliverySubmit(@ModelAttribute("model") ExpressOrder model, 
				                       RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
									   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addAttribute("orderNo", model.getOrderNo());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(model.getOrderNo());
		
		ExpressOrder expressOrder = expressOrderService.selectOne("", query);
		if(expressOrder == null){
			rst.AddError("订单不存在");
			return new ModelAndView("redirect:/"+route+"/delivery/{orderNo}");
		}
		
		//如果接单，则配置配送人员
		if(model.getStatus() == ExpressOrderStatus.Receive.getValue()){

			if(StringUtils.isBlank(model.getDeliveryPerson())){
				rst.AddError("接单请设置配送人");
				return new ModelAndView("redirect:/"+route+"/delivery/{orderNo}");
			}
			if(StringUtils.isBlank(model.getDeliveryPhone())){
				rst.AddError("接单请设置配送人电话");
				return new ModelAndView("redirect:/"+route+"/delivery/{orderNo}");
			}
		}
		String statusName = ExpressOrderStatus.getStatusName(model.getStatus());
		String message = statusName+"";
		Boolean success = false;
		try{
			//接单
			if(model.getStatus() == ExpressOrderStatus.Receive.getValue()){
				model.setDeliveryTime(SystemUtil.getAllSeconds());
			}
			else{
				model.setDeliveryPerson("");
				model.setDeliveryPhone("");
			}
			//操作日志
			this.insertOplog(request,module,"","","接单设置:"+model.getOrderNo(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

			int row = expressOrderService.updateByKey("", model);
			success = row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(success){
			rst.AddOk(message+"成功","/"+route+"/list");
		}
		else{
			rst.AddError(message+"失败","/"+route+"/list");
		}
		
		return new ModelAndView("redirect:/"+route+"/delivery/{orderNo}");
	}
	
	/**
	 * 快递完成
	 * @param map
	 * @return
	 */
	@RequestMapping("/complete/{orderNo}")
	public ModelAndView complete(@PathVariable(value="orderNo") String orderNo, ModelMap map,RedirectAttributes redAttr,HttpServletRequest request,
								 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(orderNo);
		ExpressOrder order = expressOrderService.selectByKey("", query);
		if(order == null){
			rst.AddError("订单不存在");
			return new ModelAndView("redirect:/"+route+"/list");
		}
		setLinks(map, module+"管理", "/"+route+"/list", "快递完成", "/"+route+"/complete/"+orderNo, "", "");
		setForm(map, "/"+route+"/complete/submit", null);
		map.addAttribute("orderNo", orderNo);
		
		return new ModelAndView("/express/complete");
	}
	
	/**
	 * 快递完成
	 * @param map
	 * @return
	 */
	@RequestMapping("/complete/submit")
	//public ModelAndView complete(@RequestParam(value="orderNo",required=true) String orderNo,@RequestParam(value="star",required=true) Integer star,@RequestParam(value="content",required=true) String content,RedirectAttributes redAttr){
	public ModelAndView complete(@RequestParam(value="orderNo",required=true) String orderNo,
								 @RequestParam(value="star",required=true) Integer star,
								 @RequestParam(value="content",required=true) String content,
								 ModelMap map,
								 RedirectAttributes redAttr, HttpServletRequest request,
								 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		redAttr.addAttribute("orderNo", orderNo);
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		String message = "";
		Boolean success = false;
		try{
			//操作日志
			this.insertOplog(request,module,"","","快递订单完成:"+orderNo,this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

			success = expressOrderService.complete("", orderNo, true, star, content);
			if(success){
				message = "快递订单完成成功";
			}
			else{
				message = "快递订单完成失败";
			}
		}
		catch(CustomException ce){
			message = ce.getMessage();
			logger.error(ce.getMessage());
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(success){
			rst.AddOk(message,"/"+route+"/list");
		}
		else{
			rst.AddError(message,"/"+route+"/list");
		}
		return new ModelAndView("redirect:/"+route+"/complete/{orderNo}");
	}
	
	@ResponseBody
	@RequestMapping("/complete")
	//public ResponseResult complete(@RequestParam(value="orderNo",required=true) String orderNo){
	public ResponseResult complete(@RequestParam(value="orderNo",required=true) String orderNo, HttpServletRequest request){
		ResponseResult rst = new ResponseResult();
		ExpressOrder query = new ExpressOrder();
		query.setOrderNo(orderNo);
		
		ExpressOrder model = expressOrderService.selectOne("", query);
		if(model == null){
			rst.AddError("订单不存在");
			return rst;
		}
		Boolean success = false;
		try{
			ExpressOrder entity = new ExpressOrder();
			entity.setOrderNo(orderNo);
			entity.setStatus(ExpressOrderStatus.Complete.getValue());
			entity.setCompleteTime(SystemUtil.getAllSeconds());
			//操作日志
			this.insertOplog(request,module,"","","设置订单完成:"+orderNo,this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());
			int row = expressOrderService.updateByKey("", entity);
			success = row > 0;
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		if(success){
			rst.AddOk("设置订单完成成功");
		}
		else{
			rst.AddError("设置订单完成失败");
		}
		
		return rst;
	}
}
